package com.surprise.common.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.surprise.common.annotation.LoginValidate;
import com.surprise.common.bean.Result;
import com.surprise.common.util.StringUtils;
import com.surprise.pojo.SpUserToken;
import com.surprise.service.SpUserTokenService;

/**
 * 登陆拦截器(用于LoginValidate验证用户是否登陆)
 * 
 * @author zhangceven
 *
 */
public class LoginInterceptor implements HandlerInterceptor {

	@Autowired
	private SpUserTokenService userTokenService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if (handler instanceof HandlerMethod) {
			response.setContentType("text/html;charset=UTF-8");
			HandlerMethod handlerMethod = (HandlerMethod) handler;

			// 获取请求url执行的方法上的登陆拦截注解
			LoginValidate loginValidate = handlerMethod.getMethod().getAnnotation(LoginValidate.class);
			// 判断请求url执行的方法上是否存在登陆拦截注解
			if (loginValidate != null) {
				System.out.println("开始进行登陆拦截");
				String user_id = request.getParameter("u_id");
				String serialCode = request.getParameter("serial_code");
				String authkey = request.getParameter("authkey");

				Result result = new Result();
				if (StringUtils.isEmpty(user_id) || StringUtils.isEmpty(authkey) || StringUtils.isEmpty(serialCode)) {
					result.setFailure(202, "参数错误!");
					response.getWriter().print(JSON.toJSONString(result));
					return false;
				} else {
					// 验证是否登陆
					SpUserToken obj = new SpUserToken();
					obj.setId(Integer.parseInt(user_id));
					obj.setSerialCode(serialCode);
					obj.setToken(authkey);
					SpUserToken userToken = userTokenService.selectSpUserTokenSingleByObj(obj);
					if (userToken == null) {
						result.setFailure(301, "您还没有登陆!");
						response.getWriter().print(JSON.toJSONString(result));
						return false;
					}
					return true;
				}
				
			} else {
				// 如果没有登陆拦截注解,则放行
				return true;
			}
		}

		return false;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

	}

}
